//
//  HomeLSViewController.m
//
//
//  Created by mac on 15/1/11.
//  Copyright (c) 2015年 mac. All rights reserved.
//


#import "HomeLSModel.h"
#import "SDCycleScrollView.h"
#import "ZXLoginViewController.h"
#import "DBModel.h"
#import "AddModuleViewController.h"
#import "HomeLSViewController.h"
#import "HomeCollectionViewCell.h"
#import "DecisionMakerListViewController.h"
#import "ZuZhiViewController.h"
#import "HeZhuoSheViewController.h"
#import "LPCTool.h"
#import "FinanceLSViewController.h"
#import "ProductListTableViewController.h"
#import "ZXSTechnologyViewController.h"
#import "ZXBuyNongjiViewController.h"
#import "ZXBuyNongziViewController.h"
#import "UIImageView+WebCache.h"

#import "UIImageView+ZXNetworking.h"

@interface HomeLSViewController ()<SDCycleScrollViewDelegate>
/** HomeLSModel * homeLSModel */
@property (nonatomic,strong) HomeLSModel * homeLSModel;
/** models */
@property (nonatomic,strong) NSMutableArray<DBModel *> * models;
/** firstViewDidLoad */
@property (nonatomic, assign) BOOL firstViewDidLoad;
/** NSMutableArray * imageNames */
@property (nonatomic,strong) NSMutableArray * imageNames;
/** View */
@property (weak, nonatomic) SDCycleScrollView *cycleScrollView;
/** self.imageURLStrings */
@property (nonatomic,strong) NSMutableArray<NSString *> * imageURLStrings;

/** count */
@property (nonatomic,strong) NSNumber * countNumber;
@end

@implementation HomeLSViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.firstViewDidLoad) {
        self.firstViewDidLoad = NO;
    }else{
        self.dataListDB = [[NSMutableArray alloc] initWithObjects:@"生产计划", @"我的组织", nil];
        self.imageListDB = [[NSMutableArray alloc] initWithObjects:@"home_ico_ls1", @"home_ico_ls2", nil];
        [self.models enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj.addition ==  YES) {
                [self.dataListDB addObject:obj.title];
                [self.imageListDB addObject:obj.iconName];
            }
            
            
        }];
        [self.collectionView reloadData];
    }
}
- (NSMutableArray<DBModel *> *)models {
    if (_models == nil) {
        
        NSString * fileName = [NSString stringWithFormat:@"addmodulelist%@.plist",[ZXLoginViewController getPhoneNumber]];
        // NSString * filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *plistPath1 = [paths objectAtIndex:0];
        
        NSString *filename=[plistPath1 stringByAppendingPathComponent:fileName];
        NSLog(@"filename = %@",filename);
        
        //        NSString * fileName = [NSString stringWithFormat:@"addmodulelist%@.plist",[ZXLoginView getPhoneNumber]];
        //        NSString * filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
        
        NSArray * arr = [NSArray arrayWithContentsOfFile:filename];
        if (arr == nil) {
            filename = [[NSBundle mainBundle] pathForResource:@"addmodulelist.plist" ofType:nil];
            arr = [NSArray arrayWithContentsOfFile:filename];
        }
        
        NSMutableArray * arrM = [NSMutableArray arrayWithCapacity:arr.count];
        
        [arr enumerateObjectsUsingBlock:^(NSDictionary * dict, NSUInteger idx, BOOL * _Nonnull stop) {
            DBModel * model = [DBModel modelWithDict:dict];
            [arrM addObject:model];
        }];
        _models = [arrM copy]; // 记得修改数组类型的时候也修改这里
    }
    return _models;
}
//- (NSMutableArray<DBModel *> *)models {
//    if (_models == nil) {
//        _models = [NSMutableArray array];
//        NSArray * titles = @[@"买农资", @"学农技", @"投资理财", @"找贷款", @"找农机"];
//        NSArray * subTitles = @[@"农业丰收好保证", @"更多课程技术", @"智收贷好收益", @"更多小额贷款", @"更多服务套餐"];
//        NSArray * colors = @[@"67b245", @"f49e24", @"da4c59", @"007aff", @"8174c7"];
//        NSArray * iconNames = @[@"买农资", @"学农技", @"投资理财", @"找贷款", @"找农机"];
//        for(int i = 0; i < titles.count; i++) {
//            DBModel * model = [DBModel new];
//            model.titleColorString = colors[i];
//            model.title = titles[i];
//            model.subTitle = subTitles[i];
//            model.iconName =iconNames[i];
//            model.addition = i % 2 == 0 ? YES:NO;
//            [_models addObject:model];
//        }
//    }
//    return _models;
//}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.dataListDB = [[NSMutableArray alloc] initWithObjects:@"生产计划", @"我的组织", nil];
        self.imageListDB = [[NSMutableArray alloc] initWithObjects:@"home_ico_ls1", @"home_ico_ls2", nil];
        self.colorListDB = [[NSMutableArray alloc] initWithObjects:@"0x67b245", @"0xf49e24", @"0xda4c59", @"0x007aff", @"0x8174c7", nil];
        
        
        self.imageListNM = [[NSMutableArray alloc] initWithObjects:@"买农资", @"学农技", @"投资理财", @"找贷款", @"找农机",nil];
        self.dataListNM = [[NSMutableArray alloc] initWithObjects:@"买农资", @"学农技", @"投资理财", @"找贷款", @"找农机",nil];
        self.titleListNM = [[NSMutableArray alloc] initWithObjects:@"农业丰收好保证", @"更多课程技术", @"智收贷好收益", @"更多小额贷款", @"更多服务套餐",nil];
        self.colorListNM = [[NSMutableArray alloc] initWithObjects:@"0x67b245", @"0xf49e24", @"0xda4c59", @"0x007aff", @"0x8174c7", nil];
        
        self.dataListDB = [[NSMutableArray alloc] initWithObjects:@"生产计划", @"我的组织", nil];
        self.imageListDB = [[NSMutableArray alloc] initWithObjects:@"home_ico_ls1", @"home_ico_ls2", nil];
        [self.models enumerateObjectsUsingBlock:^(DBModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj.addition ==  YES) {
                [self.dataListDB addObject:obj.title];
                [self.imageListDB addObject:obj.iconName];
            }
            
            
        }];
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addObserver:self forKeyPath:@"countNumber" options:NSKeyValueObservingOptionNew context:nil];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.title = @"首页";
    //    self.tabBarController.title = @"首页";
    self.firstViewDidLoad = YES;
    [self initViews];
    [self registerNib];
    
    [self addRequest];
}
- (void)addRequest
{
    [[ZXHTTPManager sharedManager] getHomeConfWithCompleted:^(NSDictionary *jsonDict, NSError *error) {
       
        logError
        
        NSLog(@"%@",jsonDict);
        HomeLSModel * homeLSModel = [HomeLSModel mj_objectWithKeyValues:jsonDict];
        self.homeLSModel = homeLSModel;
        [self.collectionView reloadData];
    }];
}
-(void)awakeFromNib{
    [super awakeFromNib];
    
    
}
#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", (long)index);
    
    // [self.navigationController pushViewController:[NSClassFromString(@"DemoVCWithXib") new] animated:YES];
}

- (void)initViews
{

    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150) delegate:self placeholderImage:[UIImage imageNamed:@"cyplaceholder"]];
    self.cycleScrollView = cycleScrollView;
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView.currentPageDotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
    [self.view addSubview:cycleScrollView];
    
    [[ZXHTTPManager sharedManager] getCycleViewDataCompleted:^(NSDictionary *jsonDict, NSError *error) {
       
        if (error) {
            NSLog(@"error = %@",error);
            return ;
        }
        NSLog(@"%@",jsonDict);
        NSMutableArray<NSString *> * arrM = @[].mutableCopy;
        NSArray<NSDictionary *> * arr = jsonDict[@"result"];
        for(int i = 0; i < arr.count; i++) {
           NSDictionary * dict =  arr[i];
            NSString * urlString = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down",dict[@"resourceId"]];
            [arrM addObject:urlString];
        }
        NSLog(@"%@",arrM);
        self.imageURLStrings = arrM;
        
        NSMutableArray * imageNames = @[].mutableCopy;
        self.imageNames = imageNames;
        for(int i = 0; i < arrM.count; i++) {
            [[ZXHTTPManager sharedManager] GET:arrM[i] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData * responseObject) {
                
                NSString * fileName = [NSString stringWithFormat:@"%02d.png",i];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [responseObject writeToFile:kCachePath(fileName) atomically:YES];
                    [imageNames addObject:kCachePath(fileName)];
                    NSLog(@"fileName = %@",kCachePath(fileName));
                    self.countNumber = @(imageNames.count);
                });
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"countNumber"]) {
        NSInteger count = [change[@"new"] integerValue];
        if(self.imageURLStrings.count == count){
            NSLog(@"change = %@",change[@"new"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.cycleScrollView.imageURLStringsGroup = self.imageNames;
            });
            [self removeObserver:self forKeyPath:@"countNumber"];
        }
    }
}
- (void)registerNib
{
    UINib *nib = [UINib nibWithNibName:@"HomeCollectionViewCell" bundle:nil];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:@"HomeCollectionViewCell"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-- UICollectionViewDataSource

//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"6"]||[[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"7"]) {
        // return self.dataListDB.count + 1;
        return self.homeLSModel.result.count;
    }else{
        return self.dataListNM.count + 1;
    }
}

//定义展示的Section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    long item = indexPath.item;
    static NSString *CellIdentifier = @"HomeCollectionViewCell";
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"6"]||[[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"7"]) {
        if (item < self.dataListDB.count)
        {
            cell.lblTitle1.text = self.dataListDB[item];
            cell.lblTitle2.text = @"";
            cell.image.image = [UIImage imageNamed:self.imageListDB[item]];
            cell.image2.image = nil;
        }
        else
        {
            cell.lblTitle1.text = @"";
            cell.lblTitle2.text = @"";
            cell.image.image = nil;
            cell.image2.image = [UIImage imageNamed:@"home_ico_add"];
        }
        return cell;
    }else
    {
        if (item < self.dataListNM.count)
        {
            cell.lblTitle1.text = self.dataListNM[item];
            cell.lblTitle2.text = self.titleListNM[item];
            cell.lblTitle1.textColor = [LPCTool colorWithHexString:self.colorListNM[item]];
            cell.image.image = [UIImage imageNamed:self.imageListNM[item]];
            cell.image2.image = nil;
        }
        else
        {
            cell.lblTitle1.text = @"";
            cell.lblTitle2.text = @"";
            cell.image.image = nil;
            cell.image2.image = [UIImage imageNamed:@"home_ico_add"];
        }
        return cell;
    }
}

#pragma mark--UICollectionViewDelegateFlowLayout

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH - 20) / 3 - 10, (SCREEN_WIDTH - 20) / 3 - 10);
}

#pragma mark--UICollectionViewDelegate

//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    long item = indexPath.item;
    //    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSLog(@"item = %ld",item);
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"6"]||[[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"7"]) {
        NSInteger index = self.dataListDB.count;
        if (item == index) {
            AddModuleViewController * vc = [AddModuleViewController new];
            vc.models = self.models;
            [self.navigationController pushViewController:vc animated:YES];
            return ;
        }
        switch (item)
        {
            case 0:
            {
                DecisionMakerListViewController *viewController = [[DecisionMakerListViewController alloc] initWithNibName:@"DecisionMakerListViewController" bundle:nil];
                [self.navigationController pushViewController:viewController animated:YES];
                break;
            }
            case 1:
            {
                //联社
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"6"]) {
//                    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ZuzhiViewController" bundle:nil];
                    ZuZhiViewController *zzvc = [[ZuZhiViewController alloc]init];
                    [self.navigationController pushViewController:zzvc animated:YES];
                    //合作社
                }else if([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"7"]){
                    HeZhuoSheViewController *sylbVC = [[HeZhuoSheViewController alloc] init];
                    [self.navigationController pushViewController:sylbVC animated:YES];
                }
                break;
                
            }
            default:
                break;
        }
        //非业务代表
    }else{
        //小农
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"1"]||[[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"2"]||[[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"12"]||
            //大户
            [[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"3"]||
            //农场
            [[[NSUserDefaults standardUserDefaults] objectForKey:@"userType"] isEqualToString:@"5"]            ) {
            
            NSInteger index = self.dataListNM.count;
            if (item == index) {
                AddModuleViewController * vc = [AddModuleViewController new];
                vc.models = self.models;
                [self.navigationController pushViewController:vc animated:YES];
                return ;
            }
            switch (item)
            {
                case 0:
                {
                    ZXBuyNongziViewController *vc = [[ZXBuyNongziViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 1:
                {
                    ZXSTechnologyViewController *vc = [[ZXSTechnologyViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 2:
                {
                    [self.navigationController pushViewController:[FinanceLSViewController new] animated:YES];
                    break;
                }
                case 3:
                {
                    ProductListTableViewController *viewController = [[ProductListTableViewController alloc] init];
                    [self.navigationController pushViewController:viewController animated:YES];
                    break;
                }
                case 4:
                {
                    ZXBuyNongjiViewController *vc = [[ZXBuyNongjiViewController alloc]init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
                default:
                    break;
            }
        }
        
    }
}

//返回这个UICollectionView是否可以被选择
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// cell点击变色
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
// cell点击变色
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor lightGrayColor];
}

@end
